<?php


namespace app\controllers;


use app\components\BaseAuthController;
use app\helpers\BinHelper;
use app\models\Group;
use app\models\GroupUser;
use app\models\User;
use Throwable;
use Yii;
use yii\db\Exception;
use yii\web\NotFoundHttpException;

class GroupUserController extends BaseAuthController {

    public $name = '组成员';

    public function actionIndex() {
        $group_num = $this->get('group_num');
        $group = Group::findOne(['group_num' => $group_num]);
        if (!$group) {
            Yii::$app->session->setFlash('error', "组不存在");
            return $this->redirect(['group/']);
        }

        $model = new GroupUser();
        $params = $this->getParam();
        $params['group_num'] = $group_num;
        $dataProvider = $model->search($params);

        return $this->render(compact('dataProvider'));
    }

    /**
     * @param null $id
     * @return array|bool|string
     * @throws Exception
     * @throws NotFoundHttpException
     */
    public function actionSave($id = NULL) {
        $group_num = $this->get('group_num');

        /* @var $model GroupUser */
        $model = $this->findModel($id, GroupUser::class);
        if ($model->isNewRecord) {
            $group = Group::findOne(['group_num' => $group_num]);
            if (!$group) {
                Yii::$app->session->setFlash('error', "组不存在");
                return $this->redirect(['group/']);
            }
            $model->group_num = $group_num;
        }
        if (!$model->load($this->post())) {
            return $this->render(compact('model'));
        }

        if ($model->isNewRecord) {
            if (GroupUser::findOne(['phone' => $model->phone, 'group_num' => $group_num])) {
                return $this->error('电话已经存在了');
            }
        }
        $res = $model->save();

        $output = BinHelper::run('GroupUpt', $model->group_num);
        $this->message($output);

        return $res;
    }

    public function actionDelete() {
        $id = $this->get('id');
        $model = GroupUser::findOne($id);
        if (!$model) {
            Yii::$app->session->setFlash('error', '组用户不存在');
            return $this->redirect(['group/index']);
        }

        $group_num = $model->group_num;
        $phone = $model->phone;
        try {
            $model->delete();

            $user = User::findOne(['phone' => $phone]);
            $group = Group::findOne(['group_num' => $group_num]);

            User::generateFiles($user, false);
            Group::generateFiles($group);

            $output = BinHelper::run('GroupUpt', $group_num);
            $this->message($output);

//            Yii::$app->session->setFlash('success', '删除成功');
        } catch (Exception $e) {
            Yii::$app->session->setFlash('error', $e->getMessage());
        } catch (Throwable $e) {
            Yii::$app->session->setFlash('error', $e->getMessage());
        }

        return $this->redirect(['group/index']);
    }

}